package exploitpack;

import java.awt.Color;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author jsacco
 */
public class NetworkMapper extends javax.swing.JFrame {

    // Configuration
    public String nmappath;
    public String pythonpath;
    public String ScannerOptions = "";
    Thread scannerThread;
    List<String> config = new ArrayList<>();
    StringBuilder pentestNote = new StringBuilder();
    Format formatter;
    Date date = new Date();

    /**
     * Creates new form ratWizard
     */
    public NetworkMapper() {
        try {
            initComponents();
            int lebar = this.getWidth() / 2;
            int tinggi = this.getHeight() / 2;
            int x = (Toolkit.getDefaultToolkit().getScreenSize().width / 2) - lebar;
            int y = (Toolkit.getDefaultToolkit().getScreenSize().height / 2) - tinggi;
            this.setLocation(x, y);
            this.setVisible(true);

            setDefaultCloseOperation(ExploitWizard.DISPOSE_ON_CLOSE);
            getContentPane().setBackground(Color.WHITE);
            setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/exploitpack/resources/bug.png")));
            jTextFieldTargetH.setText(Inet4Address.getLocalHost().getHostAddress());
            if (new File("exploits/rockyou").exists()) {
                jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exploitpack/resources/uppro.png"))); // NOI18N
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(NetworkMapper.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField3 = new javax.swing.JTextField();
        jTextField5 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTextFieldRatName = new javax.swing.JTextField();
        jTextFieldTargetH = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox<>();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaLog = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();

        jTextField3.setText("jTextField1");

        jTextField5.setText("jTextField1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Exploit Pack - Network mapper");
        setResizable(false);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exploitpack/resources/up.png"))); // NOI18N

        jButton1.setText("Cancel");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Execute");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("<html>Exploit Pack network scan feature will help you map your network, create <br>your targets list and identify possible threats within your environment.<br> For every host a new XML log file will be created, that you can use later on to<br> match templates and identify changes within your network infrastructure..</html>");

        jLabel3.setText("Scan name:");
        jLabel3.setToolTipText("");

        jLabel5.setText("IP / Range:");

        jTextFieldRatName.setText("My network scan");

        jTextFieldTargetH.setText("127.0.0.1");

        jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/exploitpack/resources/network.png"))); // NOI18N

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "24", "16", "8" }));

        jTextAreaLog.setEditable(false);
        jTextAreaLog.setBackground(java.awt.Color.black);
        jTextAreaLog.setColumns(20);
        jTextAreaLog.setForeground(java.awt.Color.green);
        jTextAreaLog.setRows(5);
        jTextAreaLog.setText("- There is no scan running at this time.\n- Log empty.");
        jScrollPane1.setViewportView(jTextAreaLog);

        jLabel4.setFont(jLabel4.getFont().deriveFont(jLabel4.getFont().getStyle() | java.awt.Font.BOLD));
        jLabel4.setText("Status log of current scan:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextFieldTargetH, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jTextFieldRatName))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(9, 9, 9)
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel11))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jTextFieldRatName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldTargetH, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
                        .addComponent(jLabel4)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 444, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        jLabel2.getAccessibleContext().setAccessibleName("<html>This shell wizard helps you create your  personalized agent to use with Exploit Pack.  <br>The created script, if needed, could include also a custom shellcode<br> and converted into an executable file.</html>");

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        FileReader fstream = null;
        formatter = new SimpleDateFormat("hh:mm:ss");
        String LogTime = "[" + new Timestamp(Calendar.HOUR) + "]";

        try {
            // Read config file
            fstream = new FileReader("output/" + "config" + ".ep");
            BufferedReader in = new BufferedReader(fstream);
            String stringToAppend;
            while ((stringToAppend = in.readLine()) != null) {
                config.add(stringToAppend);
            }
            pythonpath = config.get(0);
            nmappath = config.get(1);
            ScannerOptions = config.get(2);

            scannerThread = new Thread("scannerThread") {
                @Override
                public void run() {
                    try {
                        // Exec wav RAT
                        AudioInputStream sourceAux;
                        AudioFormat f;
                        DataLine.Info inputAux;
                        File inputFileAux = new File("data/newauxiliarydeployed.wav");
                        Clip c;
                        sourceAux = AudioSystem.getAudioInputStream(inputFileAux);
                        f = sourceAux.getFormat();
                        inputAux = new DataLine.Info(Clip.class, f);
                        c = (Clip) AudioSystem.getLine(inputAux);
                        c.open(sourceAux);
                        c.start();

                        // Exec scan
                        jTextAreaLog.setText(LogTime + " " + "Please wait, the scan could take a few minutes" + "\r\n");
                        jTextAreaLog.append(LogTime + " " + "Scan has been started, running.." + "\r\n");
                        String cmd = nmappath + " " + ScannerOptions + " " + jTextFieldTargetH.getText() + " -oX log/" + jTextFieldTargetH.getText() + ".xml";
                        Process proc = Runtime.getRuntime().exec(cmd);
                        try (BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getErrorStream()))) {
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                Logger.getLogger(MainFrame.class
                                        .getName()).log(Level.SEVERE, null, line);
                            }
                        }

                        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder dBuilder;
                        dBuilder = dbFactory.newDocumentBuilder();
                        Document doc = dBuilder.parse(new File("log/" + jTextFieldTargetH.getText() + ".xml"));
                        doc.getDocumentElement().normalize();
                        NodeList nList = doc.getElementsByTagName("port");
                        String openports = null;
                        for (int temp = 0; temp < nList.getLength(); temp++) {
                            Node nNode = nList.item(temp);
                            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                                // Create target
                                FileWriter fstream = null;
                                try {
                                    String name = jTextFieldTargetH.getText();
                                    fstream = new FileWriter("exploits/" + name + ".xml");
                                    BufferedWriter out = new BufferedWriter(fstream);
                                    java.util.Date date = new java.util.Date();
                                    out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                                    out.write("<Module><Exploit NameXML=\""
                                            + name
                                            + "\" CodeName=\"" + name + ".txt" + "\"  Platform=\"" + "windows" + "\" Service=\"" + "" + "\" Type=\"" + "notepad" + "\" RemotePort=\"" + "" + "\" LocalPort=\"\" ShellcodeAvailable=\"" + "" + "\" ShellPort=\"4444\" SpecialArgs=\"" + "" + "\"></Exploit>");
                                    out.write("<Information Author=\"" + "ExploitPack" + "\" Date=\""
                                            + new Timestamp(date.getTime())
                                            + "\" Vulnerability=\""
                                            + "none"
                                            + "\">\r\n" + "" + "</Information><Targets>" + "" + "</Targets></Module>");
                                    out.close();
                                    fstream = new FileWriter("exploits/code/" + name + ".txt");
                                    BufferedWriter outCode = new BufferedWriter(fstream);

                                    pentestNote.insert(0, "# Pentest notes for: " + jTextFieldTargetH.getText() + "\n");
                                    pentestNote.append(openports);
                                    outCode.write(pentestNote.toString().replaceAll("^,", "").replaceAll(",,", ",").replaceAll(",$", "").replaceAll("null", ""));
                                    outCode.close();

                                } catch (IOException ex) {
                                    Logger.getLogger(Notepad.class
                                            .getName()).log(Level.SEVERE, null, ex);
                                } finally {
                                    try {
                                        fstream.close();
                                    } catch (IOException ex) {
                                        Logger.getLogger(Notepad.class
                                                .getName()).log(Level.SEVERE, null, ex);
                                    }
                                }
                            }
                        }
                        jTextAreaLog.append(LogTime + " " + "The scan to: " + jTextFieldTargetH.getText() + " has finished." + "\r\n");

                    } catch (IOException | SAXException | ParserConfigurationException ex) {
                        Logger.getLogger(MainFrame.class
                                .getName()).log(Level.SEVERE, null, ex);
                        JOptionPane.showMessageDialog(null, "Nmap not found on your system, please check your preferences.", "Exploit Pack says:", JOptionPane.ERROR_MESSAGE);

                    } catch (UnsupportedAudioFileException | LineUnavailableException ex) {
                        Logger.getLogger(MainFrame.class
                                .getName()).log(Level.SEVERE, null, ex);
                    }
                }
            };
            scannerThread.start();
            jTextAreaLog.append(LogTime + " " + "XML Log files saved under exploits/ folder" + "\r\n");
            jTextAreaLog.append(LogTime + " " + "Refresh your targets list to show the results" + "\r\n");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NetworkMapper.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(NetworkMapper.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fstream.close();
            } catch (IOException ex) {
                Logger.getLogger(NetworkMapper.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;

                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NetworkMapper.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NetworkMapper.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NetworkMapper.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NetworkMapper.class
                    .getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NetworkMapper().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox<String> jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextArea jTextAreaLog;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextFieldRatName;
    private javax.swing.JTextField jTextFieldTargetH;
    // End of variables declaration//GEN-END:variables
}
